package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"zhihu-new/models/cache"
	"zhihu-new/models/mysql"
	"zhihu-new/pkg"

	"zhihu-new/zhihurpc/internal/svc"
	"zhihu-new/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *zhihurpc.ForgetPasswordRequest) (*zhihurpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"forgetPassword"+in.Mobile)
	if get.Val() != in.CaptSms {
		return nil, fmt.Errorf("验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该手机号未注册")
	}

	if in.Password != in.PasswordNew {
		return nil, fmt.Errorf("两次密码输入不一致,请重新输入")
	}

	user = mysql.User{
		Model: gorm.Model{
			ID: user.ID,
		},
		Password: pkg.Md5(in.Password),
	}

	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("密码修改失败")
	}
	//成功后删除验证码缓存
	cache.Rdb.Get(l.ctx, "sendSms"+"forgetPassword"+in.Mobile)
	return &zhihurpc.ForgetPasswordResponse{UserId: int64(user.ID)}, nil
}
